<template>

    <div>
        <el-button type="danger" :icon="Plus" style="float: left;;margin-left: 10px;"
            @click="result">新增</el-button>&emsp;
        <el-button type="danger" :icon="Check" style="float: left;;margin-left: 10px;"
            @click="save()">保存</el-button>&emsp;
        <el-button type="danger" :icon="Back" style="float: left;;margin-left: 10px;"
            @click="delDomain()">撤销</el-button>&emsp;
        <el-button type="danger" :icon="Delete" style="float: left;;margin-left: 10px;"
            @click="DeleteLoge()">删除</el-button>
    </div>
    <br />
    <div>
        <span style="font-weight: bold;"> 转种日期:</span>&emsp;
        <el-date-picker v-model="form.MotherData" type="date" style="width: 200px;border: none;"
            placeholder="日期" />&emsp;&emsp;
        <span style="font-weight: bold;"> 单据号: </span>&emsp;
        <el-input style="width: 200px;" v-model="form.DocumentNo" placeholder="-- --" />
        <span style="font-weight: bold;"> 流水号: </span>&emsp;
        <el-input style="width: 200px;" v-model="form.SerialNo" placeholder="-- --" />
    </div>
    <br />
    <hr style="font-size: 20px;" />
    <br />

    <div class="table-container" style=" height: 400px;position: relative;">
        <table style="border-collapse: collapse;">
            <tr>
                <td>序号</td>
                <td>育成羊耳号</td>
                <td>转入栋舍</td>
                <td>转入栏位</td>
                <td>当前栋舍</td>
                <td>当前栏位</td>
                <td>性别</td>
                <td>转种日龄</td>
            </tr>
            <tr v-for="(ruleForm, index) in loge.healthArray">
                <td>{{ index + 1 }}</td>
                <td>
                    <el-select style="width: 100px" v-model="ruleForm.EweID" placeholder="请选择">
                        <el-option v-for="item in eweData" :label="item.earNumber" :value="item.sleepInforId"
                            @click="getearMsg(index)" />
                    </el-select>
                </td>
                <td>
                    <el-select style="width: 100px" v-model="ruleForm.CurrentBarn" placeholder="请选择">
                        <el-option v-for="item in Recordcottage" :label="item.cottageName" :value="item.cottagesId" />
                    </el-select>
                </td>
                <td>
                    <el-select style="width: 100px" v-model="ruleForm.CurrentPen" placeholder="请选择">
                        <el-option v-for="item in Fields" :label="item.fieIdName" :value="item.fieIdId" />
                    </el-select>
                </td>
                <td>
                    <el-select style="width: 100px" v-model="ruleForm.TransferBarn" placeholder="请选择">
                        <el-option v-for="item in Recordcottage2" :label="item.cottageName" :value="item.cottagesId"
                            @click="getFields2(ruleForm.TransferBarn, index)" />
                    </el-select>
                </td>
                <td>
                    <el-select style="width: 100px" v-model="ruleForm.TransferPen" placeholder="请选择">
                        <el-option v-for="item in Fields2[index]" :label="item.fieIdName" :value="item.fieIdId" />
                    </el-select>
                </td>
                <td>
                    <el-select style="width: 100px" v-model="ruleForm.Gender" placeholder="请选择">
                        <el-option label="公" :value="1" />
                        <el-option label="母" :value="2" />
                    </el-select>
                </td>
                <td>
                    <el-input style="width: 100px" v-model="ruleForm.PregnancyDays"></el-input>
                </td>

            </tr>
        </table>

    </div>
    <div style="bottom: 0; left: 0;width: 100%;;">
        <hr>
        <!-- <span>&emsp; 合计</span>
            <hr> -->
        <el-button link type="danger" :icon="Plus" style="float: left;;margin-left: 10px;"
            @click="addDomain">增行</el-button>&emsp;
        <el-button link type="danger" :icon="Check" style="float: left;;margin-left: 10px;"
            @click="delDomain">删行</el-button>&emsp;
        <br />
        <hr>
        <span style="vertical-align: top;width: 5%;">&emsp; 备注</span>&emsp;
        <el-input v-model="form.Message" type="textarea" style="width: 85%;" />
    </div>


</template>
<script lang="ts" setup>
import {
    Check,
    Delete,
    Plus,
    Back,
} from '@element-plus/icons-vue'
import { reactive, ref, onMounted } from 'vue';
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';
//调用持久化
import { useCounterStore } from '@/stores/counter';
const counterStore = useCounterStore();
const route = useRoute();
const router = useRouter();


//钩子函数
onMounted(() => {
    getParturitionDifficulty()//分娩难易度
    getFatSheepBatch()//羔羊批次
    geteweData()//耳号
    getRecordcottage()//栋舍
    getserialNumber()//流水号
})
const loge = reactive({
    healthArray: <any>[],
});

//增行
const addDomain = () => {
    loge.healthArray.push(
        reactive({
            "createId": counterStore.employeeId,
            "createTime": new Date(),
            updateId: null,
            updateTime: null,
            deleteId: null,
            deletes: false,
            deleteTime: null,
            examId: null,
            examTime: null,
            "motherGivingBirthId": 0,
            "leader": form.Leader,
            "motherData": form.MotherData,
            "eweID": 0,
            "pregnancyDays": 0,
            "deliveryEase": 0,
            "batchNumber": 0,
            "maternalBehavior": 0,
            "lactation": true,
            "mastitis": true,
            "litterID": 0,
            "healthyLambsCount": 0,
            "weakLambsCount": 0,
            "deformedLambsCount": 0,
            "stillbornLambsCount": 0,
            "mummifiedLambsCount": 0,
            "malformedFetusCount": 0,
            "liveLambs": 0,
            "litterTotalWeight": 0,
            "gender": 0,
            "currentBarn": 0,
            "currentPen": 0,
            "transferBarn": 0,
            "transferPen": 0,
            "notes": form.Message,
            "documentNo": form.DocumentNo,
            "serialNo": form.SerialNo.toString(),

        }));
    console.log(loge.healthArray);
};

//新增 
const result = () => {
    loge.healthArray = []
    addDomain();
}
const DeleteLoge = () => {
    loge.healthArray = []
}


//减行撤销
const delDomain = () => {
    loge.healthArray.splice(loge.healthArray.length - 1, 1)
}
//获取羊只信息
const form = reactive({
    Leader: "",
    MotherData: '',
    Message: '',
    DocumentNo: '',
    SerialNo: '',
    BreedStatuId: '',
})
//获取羊只信息
const updates = reactive({
    EweID: '',
    Gender: '',
    CurrentBarn: '',
    CurrentPen: '',
})
//#region 
/*------------下拉框------------*/
//获取分娩难易度
const ParturitionDifficulty = ref<any>([]);
const getParturitionDifficulty = () => {
    axios.get('http://localhost:5039/api/ProductionManagement/ParturitionDifficultyList').then(res => {
        ParturitionDifficulty.value = res.data.data;
    })
}
//获取肥羊品种
const FatSheepBatch = ref<any>([]);
const getFatSheepBatch = () => {
    axios.get('http://localhost:5039/api/ProductionManagement/FatSheepBatchList').then(res => {
        FatSheepBatch.value = res.data.data;
    })
}

//获取耳号
const eweData = ref<any>([]);
const geteweData = () => {
    axios.get('http://localhost:5039/api/SleepBegin/SelectEarFeMale').then(res => {
        eweData.value = res.data.data;
    })
}
//获取栋舍
const Recordcottage = ref<any>([]);
const Recordcottage2 = ref<any>([]);
const getRecordcottage = () => {
    axios.post('http://localhost:5039/api/Cottages/CottageList', {
    }).then(res => {
        Recordcottage.value = res.data.data;
        Recordcottage2.value = res.data.data;
    })
}
//获取栏位
const Fields = ref<any>([]);
const Fields2 = ref<any>([]);
const getFields = (id: number) => {
    console.log(id);
    axios.post('http://localhost:5039/api/Cottages/SearchFields', {
        "cottagesId": id,
        "pageIndex": 1,
        "pageSize": 100000000
    }).then(res => {
        console.log(res.data.data);
        Fields.value = res.data.data;
    })
}
const getFields2 = (id: number, index: any) => {
    Fields2.value[index] = [];
    axios.post('http://localhost:5039/api/Cottages/SearchFields', {
        "cottagesId": id,
        "pageIndex": 1,
        "pageSize": 100000000
    }).then(res => {
        Fields2.value[index] = res.data.data
        loge.healthArray[index].TransferPen = '';
        console.log(Fields2.value);
    })
}


//#region 耳号反填

//通过耳号和状态获取妊娠 的信息
const getearMsg = (index: any) => {
    const selectedEweID = loge.healthArray[index].EweID; // 获取选中的 EweID
    console.log(selectedEweID);
    axios.get('http://localhost:5039/api/ProductionManagement/EarMasList', {
        params: {
            SleepInforId: selectedEweID,
            BreedStatuId: 4
        }
    }).then(res => {
        console.log(res.data.item);
        updates.EweID = res.data.item.sleepInforId;
        updates.Gender = res.data.item.gender;
        updates.CurrentBarn = res.data.item.recordcottageId;
        updates.CurrentPen = res.data.item.fieIdId;
        handleUpdate()//调用更新数据的方法
    })

}
// 例子：通过表单输入更新数据
const handleUpdate = () => {
    const eweID = updates.EweID; // 假设你从表单获取到的 EweID
    const gender = updates.Gender; // 假设你从表单获取到的 Gender
    const currentBarn = updates.CurrentBarn; // 假设你从表单获取到的 CurrentBarn
    const currentPen = updates.CurrentPen; // 假设你从表单获取到的 CurrentPen
    console.log(eweID, gender, currentBarn, currentPen);
    updateFieldsByEweID(eweID, gender, currentBarn, currentPen);
};
const updateFieldsByEweID = (eweID: string, gender: string, currentBarn: string, currentPen: string) => {
    // 遍历 healthArray 找到 EweID 对应的项并更新
    const healthItem = loge.healthArray.find((item: any) => item.EweID === eweID);

    if (healthItem) {
        healthItem.Gender = gender;
        healthItem.CurrentBarn = currentBarn;
        getFields(healthItem.CurrentBarn)

        healthItem.CurrentPen = currentPen;

    } else {
        console.log(`没有找到EweID为 ${eweID} 的数据`);
    }
};
/*------------流水号------------*/
const getserialNumber = () => {
    axios.post('http://localhost:5039/api/ProductionManagement/GetId', {}).then(res => {
        form.SerialNo = res.data;
    })
}

//#endregion



//#region 保存
const save = () => {
    let obj = {
        motherGivingBirth: loge.healthArray
    }
    axios.post('http://localhost:5039/api/ProductionManagement/MotherGivingBirthAdd', obj).then(res => {
        if (res.data.code == 0) {
            console.log('保存成功');
            router.push('/Descendants_transferList')
        }
    })
}


//#endregion


</script>



<style scoped>
.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}

/* 设置第一行的 td 顶部边框加粗并设置为红色 */
table tr:first-child td {
    border-top: 3px solid red;
    /* 设置顶部边框为3px宽度的红色 */
    padding: 10px;
    text-align: center;
}

/* 设置 td 的样式 */

table td {
    padding: 10px;
    border: 1px solid #ccc;
    text-align: center;
    font-size: 14px;
    height: 60px;
    width: 150px;
    white-space: nowrap;
    /* 防止内容换行 */
}

/* 可选：为 table 添加样式 */
table {
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed;
}



/*______________________________________________________*/

.table-container {
    max-width: 100%;
    overflow-x: auto;
    /* 启用水平滚动 */
    margin: 20px 0;
    /* 设置容器的外边距 */
}
</style>